"""
法大大 接口
"""
import requests
import json
import datetime
import uuid
from urllib.parse import urlencode

from .MsgDigest import MsgDigest
from .ConfigParser import ConfigParser


class FddApi:
    def __init__(self):
        config = ConfigParser()
        self.baseUrl = config.get_url()
        self.app_id = config.get_app_id()
        self.app_secret = config.get_app_secret()
        self.version = config.get_version()
        self.now = datetime.datetime.now()
        self.notify_url = config.get_notify_url()
        self.return_url = config.get_return_url()
        # 公共参数
        self.timestamp_str = self.now.strftime('%Y%m%d%H%M%S')
        self.public_info = {
            "app_id": self.app_id,
            "v": self.version,
            "app_secret": self.app_secret,
            "timestamp": self.timestamp_str
        }

    def request(self, **kwargs):
        """
        发送请求
        """
        url = kwargs.get("url")
        methods = kwargs.get("methods")
        payload = kwargs.get("payload")
        response = requests.request(method=methods, url=url, data=payload)
        # print(response)
        # return response
        result = json.loads(response.text)
        # # code = result.get("code")
        # # print(result)
        return result
        # if code == "1":
        #     return result
        # else:
        #     raise ValueError(result.get("msg"))

    def url_request(self, **kwargs):
        """
        地址 查看
        """
        url = kwargs.get("url")
        methods = kwargs.get("methods")
        payload = kwargs.get("payload")
        response = requests.request(method=methods, url=url, data=payload)
        return response

    def register(self, **kwargs):
        """
        注册
        """
        # 取参
        # --- start ---
        open_id = kwargs.get("open_id")
        account_type = kwargs.get("account_type")
        # --- end ---
        url = self.baseUrl + "account_register.api"
        params = {
            "open_id": open_id,
            "account_type": account_type
        }
        digest_info = self.public_info
        digest_info["payload"] = params
        msg_digest = MsgDigest().get_digest(**digest_info)
        payload = {
            "msg_digest": msg_digest,
            "app_id": self.app_id,
            "timestamp": self.timestamp_str,
            "v": self.version
        }
        payload.update(params)
        return self.request(url=url, methods="post", payload=payload)

    def get_person_verify_url(self, **kwargs):
        """
        获取个人实名认证地址
        """
        # 取参
        # --- start ---
        customer_id = kwargs.get("customer_id")
        customer_name = kwargs.get("customer_name")
        customer_ident_no = kwargs.get("customer_ident_no")
        mobile = kwargs.get("mobile")
        area_code = kwargs.get("area_code")
        ident_front_path = kwargs.get("ident_front_path")
        ident_back_path = kwargs.get("ident_back_path")
        return_url_params = kwargs.get("return_url_params")
        # --- end ---
        url = self.baseUrl + "get_person_verify_url.api"
        return_url = self.return_url
        params = {
            "customer_id": customer_id,
            "verified_way": "4",
            "page_modify": "1",
            "notify_url": self.notify_url,
            "return_url": self.return_url,
            "customer_ident_type": "0",
            "id_photo_optional": "1",
            "result_type": "2",
            "cert_flag": "1",
            "option": "add",
            "cert_type": "0",
            "is_mini_program": "0",
            "lang": "zh",
        }
        if return_url_params is not None:
            return_url = self.return_url + "?" + urlencode(return_url_params)
            params["return_url"] = return_url
        if customer_name is not None:
            params["customer_name"] = customer_name
        if customer_ident_no is not None:
            params["customer_ident_no"] = customer_ident_no
        if mobile is not None:
            params["mobile"] = mobile
        if area_code is not None:
            params["area_code"] = area_code
        if ident_front_path is not None:
            params["ident_front_path"] = ident_front_path
        if ident_back_path is not None:
            params["ident_back_path"] = ident_back_path
        digest_info = self.public_info
        digest_info["payload"] = params
        msg_digest = MsgDigest().get_digest(**digest_info)
        payload = {
            "msg_digest": msg_digest,
            "app_id": self.app_id,
            "timestamp": self.timestamp_str,
            "v": self.version
        }
        payload.update(params)
        return self.request(url=url, methods="post", payload=payload)

    def get_company_verify_url(self, **kwargs):
        """
        获取企业实名认证地址
        """
        # 取参
        # --- start ---
        customer_id = kwargs.get("customer_id")  # 必传
        # CompanyInfo 企业信息
        company_name = kwargs.get("company_name")  # 企业名称
        credit_no = kwargs.get("credit_no")  # 统一社会信用代码
        credit_image_path = kwargs.get("credit_image_path")  # 统一社会信用代码证件照路径
        # LegalInfo 法人信息
        legal_name = kwargs.get("legal_name")  # 法人姓名
        legal_id_front_path = kwargs.get("legal_id_front_path")
        legal_id_back_path = kwargs.get("legal_id_back_path")
        # --- end ---
        url = self.baseUrl + "get_company_verify_url.api"
        params = {
            "customer_id": customer_id,
            "verified_way": "3",
            # "m_verified_way": "4",
            # "legal_allow_company_verify_way": "1",
            # "id_photo_optional": "1",
            "page_modify": "1",
            "company_info": json.dumps({
                "company_name": company_name,
                "credit_no": credit_no,
                "credit_image_path": credit_image_path,
            }),
            "legal_info": json.dumps({
                "legal_name": legal_name,
                "legal_id_front_path": legal_id_front_path,
                "legal_id_back_path": legal_id_back_path
            }),
            "notify_url": self.notify_url,
            "return_url": self.return_url,
            "cert_flag": "1",
            "is_mini_program": "0",
            "lang": "zh",
        }
        digest_info = self.public_info
        digest_info["payload"] = params
        msg_digest = MsgDigest().get_digest(**digest_info)
        payload = {
            "msg_digest": msg_digest,
            "app_id": self.app_id,
            "timestamp": self.timestamp_str,
            "v": self.version
        }
        payload.update(params)
        return self.request(url=url, methods="post", payload=payload)

    def uploadtemplate(self, **kwargs):
        """
        上传模板
        """
        template_name = kwargs.get("template_name")
        template_id = kwargs.get("template_id")
        doc_url = kwargs.get("doc_url")
        url = self.baseUrl + "uploadtemplate.api"
        params = {
            "template_id": template_id,
            "template_name": template_name,
            "doc_url": doc_url
        }
        digest_info = self.public_info
        digest_info["template_id"] = template_id
        msg_digest = MsgDigest().get_digest_file(**digest_info)
        payload = {
            "msg_digest": msg_digest,
            "app_id": self.app_id,
            "timestamp": self.timestamp_str,
            "v": self.version
        }
        payload.update(params)
        return self.request(url=url, methods="post", payload=payload)

    def generate_contract(self, **kwargs):
        """
        模板填充
        """
        doc_title = kwargs.get("doc_title")
        template_id = kwargs.get("template_id")
        contract_id = kwargs.get("contract_id")
        parameter_map = kwargs.get("parameter_map")
        url = self.baseUrl + "generate_contract.api"
        params = {
            "doc_title": doc_title,
            "template_id": template_id,
            "contract_id": contract_id,
            "parameter_map": parameter_map,
            "fill_type": "0"
        }
        digest_info = self.public_info
        digest_info["template_id"] = template_id
        digest_info["contract_id"] = contract_id
        digest_info["parameter_map"] = parameter_map
        msg_digest = MsgDigest().generate_contract_digest(**digest_info)
        payload = {
            "msg_digest": msg_digest,
            "app_id": self.app_id,
            "timestamp": self.timestamp_str,
            "v": self.version
        }
        payload.update(params)
        return self.request(url=url, methods="post", payload=payload)

    def uploaddocs(self, **kwargs):
        """
        上传合同
        """
        contract_id = kwargs.get("contract_id")
        doc_title = kwargs.get("doc_title")
        doc_url = kwargs.get("doc_url")
        url = self.baseUrl + "uploaddocs.api"
        params = {
            "contract_id": contract_id,
            "doc_title": doc_title,
            "doc_url": doc_url,
            "doc_type": ".pdf"
        }
        digest_info = self.public_info
        digest_info["contract_id"] = contract_id
        msg_digest = MsgDigest().uploaddocs_digest(**digest_info)
        payload = {
            "msg_digest": msg_digest,
            "app_id": self.app_id,
            "timestamp": self.timestamp_str,
            "v": self.version
        }
        payload.update(params)
        return self.request(url=url, methods="post", payload=payload)

    def viewContract(self, **kwargs):
        """
        查看合同
        """
        contract_id = kwargs.get("contract_id")
        url = self.baseUrl + "viewContract.api"
        params = {
            "contract_id": contract_id,
        }
        digest_info = self.public_info
        digest_info["contract_id"] = contract_id
        msg_digest = MsgDigest().uploaddocs_digest(**digest_info)
        payload = {
            "msg_digest": msg_digest,
            "app_id": self.app_id,
            "timestamp": self.timestamp_str,
            "v": self.version
        }
        payload.update(params)
        url_params = urlencode(payload)
        url = url + "?" + url_params
        return self.url_request(url=url, methods="get", payload={})

    def extsign(self, **kwargs):
        """
        签署合同
        """
        transaction_id = kwargs.get("transaction_id")
        contract_id = kwargs.get("contract_id")
        customer_id = kwargs.get("customer_id")
        doc_title = kwargs.get("doc_title")
        url = self.baseUrl + "extsign.api"
        params = {
            "contract_id": contract_id,
            "transaction_id": transaction_id,
            "customer_id": customer_id,
            "doc_title": doc_title,
            "mobile_sign_type": "2",
        }
        digest_info = self.public_info
        digest_info["customer_id"] = customer_id
        digest_info["transaction_id"] = transaction_id
        msg_digest = MsgDigest().extsign_digest(**digest_info)
        payload = {
            "msg_digest": msg_digest,
            "app_id": self.app_id,
            "timestamp": self.timestamp_str,
            "v": self.version
        }
        payload.update(params)
        url_params = urlencode(payload)
        url = url + "?" + url_params
        return self.url_request(url=url, methods="get", payload={})

    def apply_cert(self, **kwargs):
        """
        绑定实名信息
        """
        customer_id = kwargs.get("customer_id")
        verified_serialno = kwargs.get("verified_serialno")
        url = self.baseUrl + "apply_cert.api"
        params = {
            "customer_id": customer_id,
            "verified_serialno": verified_serialno
        }
        digest_info = {
            "payload": params,
            "app_id": "406595",
            "timestamp": timestamp_str,
            "v": "2.0",
            "app_secret": "lpeFgRmpkuH7JhbSqsGMWqkb"
        }
        msg_digest = MsgDigest().get_digest(**digest_info)
        payload = {
            "msg_digest": msg_digest,
            "app_id": "406595",
            "timestamp": timestamp_str,
            "v": "2.0",
            "customer_id": customer_id,
            "verified_serialno": verified_serialno
        }
        return self.request(url=url, methods="get", payload=payload)

    def contractFiling(self, **kwargs):
        """
        合同归档
        """
        contract_id = kwargs.get("contract_id")
        url = self.baseUrl + "contractFiling.api"
        params = {
            "contract_id": contract_id,
        }
        digest_info = self.public_info
        digest_info["contract_id"] = contract_id
        msg_digest = MsgDigest().uploaddocs_digest(**digest_info)
        payload = {
            "msg_digest": msg_digest,
            "app_id": self.app_id,
            "timestamp": self.timestamp_str,
            "v": self.version
        }
        payload.update(params)
        return self.url_request(url=url, methods="post", payload=payload)

    def downLoadContract(self, **kwargs):
        """
        合同下载
        """
        contract_id = kwargs.get("contract_id")
        url = self.baseUrl + "downLoadContract.api"
        params = {
            "contract_id": contract_id
        }
        digest_info = {
            "payload": params,
            "app_id": "406595",
            "timestamp": timestamp_str,
            "v": "2.0",
            "app_secret": "lpeFgRmpkuH7JhbSqsGMWqkb"
        }
        msg_digest = MsgDigest().get_digest(**digest_info)
        payload = {
            "msg_digest": msg_digest,
            "app_id": "406595",
            "timestamp": timestamp_str,
            "v": "2.0",
            "contract_id": contract_id,
        }
        return self.request(url=url, methods="post", payload=payload)
